package com.todo.event.activity.application.backend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.entity.response.BizPageResponse;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.entity.response.page.PageResult;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.event.activity.application.backend.service.EventDetailBackendService;
import com.todo.event.activity.application.convert.EventActivityConvert;
import com.todo.event.activity.application.entity.bo.EventDetailBO;
import com.todo.event.activity.application.entity.bo.EventInfoBO;
import com.todo.event.activity.application.entity.condition.EventInfoConditionBO;
import com.todo.event.activity.application.entity.model.EventInfoModel;
import com.todo.event.activity.application.service.EventDetailService;
import com.todo.event.activity.application.service.impl.EventDataService;
import com.todo.event.activity.common.enums.EventDetailStatusEnum;
import com.todo.event.activity.iface.backend.request.*;
import com.todo.event.activity.iface.backend.response.EventDetailResp;
import com.todo.event.activity.iface.backend.response.EventInfoResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author azhebuxing
 * @date 2025/1/11 21:24
 * @description
 */
@Slf4j
@Service
public class EventDetailBackendServiceImpl implements EventDetailBackendService {

    @Resource
    private EventDetailService eventDetailService;
    @Resource
    private EventDataService eventDataService;


    @Override
    public BizResponse<Boolean> insertEventDetail(InsertEventDetailReq req) {
        EventDetailBO eventDetailBO = EventActivityConvert.convertToEventDetailBO(req);
        Boolean inserted = eventDetailService.insertEventDetail(eventDetailBO);
        log.info("EventDetailBackendService#insertEventDetail 新增事件详情完成 入参：【{}】，出参：【{}】", JSONObject.toJSONString(req), inserted);
        return BizResponse.success(inserted);
    }

    @Override
    public BizResponse<Boolean> updateEventDetail(UpdateEventDetailReq req) {
        EventDetailBO eventDetailBO = EventActivityConvert.convertToEventDetailBO(req);
        Boolean updated = eventDetailService.updateEventDetail(eventDetailBO);
        log.info("EventDetailBackendService#updateEventDetail 更新事件详情完成 入参：【{}】，出参：【{}】", JSONObject.toJSONString(req), updated);
        return BizResponse.success(updated);
    }

    @Override
    public BizResponse<Boolean> removeEventDetailById(RemoveEventDetailByIdReq req) {
        EventDetailBO eventDetailBO = eventDetailService.queryEventDetail(req.getEventId());
        if (eventDetailBO == null) {
            log.info("EventDetailBackendService#removeEventDetailById 删除事件详情完成，数据不存在 入参：【{}】", JSONObject.toJSONString(req));
            return BizResponse.success();
        }
        if (!eventDetailBO.getCreateUser().equals(req.get_staff().getUsername())) {
            log.error("EventDetailService#removeEventDetailById 删除事件详情失败，当前用户无权限操作 eventDetailBO：【{}】", JSONObject.toJSONString(eventDetailBO));
            throw new BizException(BizErrorCodeEnum.ILLEGAL_OPERATION, "当前用户无权限操作");
        }
        Boolean removed = eventDetailService.removeEventDetailById(req.getEventId());
        log.info("EventDetailBackendService#removeEventDetailById 删除事件详情完成 入参：【{}】，出参：【{}】", JSONObject.toJSONString(req), removed);
        return BizResponse.success(removed);
    }

    @Override
    public BizResponse<String> testEventDetailProperty(TestEventDetailPropertyReq req) {
        EventDetailBO eventDetailBO = eventDetailService.queryEventDetail(req.getEventId());
        if (eventDetailBO == null) {
            log.error("EventDetailBackendService#testEventDetailProperty 查询事件详情失败 入参：【{}】", JSONObject.toJSONString(req));
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        if (eventDetailBO.getStatus().equals(EventDetailStatusEnum.RUNNING)) {
            log.error("EventDetailBackendService#testEventDetailProperty 当前事件运行中，无需测试 入参：【{}】", JSONObject.toJSONString(req));
            throw new BizException(BizErrorCodeEnum.NOT_SUPPORT_OPERATE_STATUS, "当前事件运行中，无需再次验证");
        }
        EventInfoModel eventInfoModel = eventDataService.buildAndeGetExecuteModel(eventDetailBO, JSONObject.parseObject(req.getTestPayload()));
        if (eventInfoModel == null) {
            log.error("EventDetailBackendService#testEventDetailProperty 构建事件详情失败 入参：【{}】", JSONObject.toJSONString(req));
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        Boolean updated = eventDetailService.updateEventDetailStatus(eventDetailBO.getId(), eventDetailBO.getStatus(), EventDetailStatusEnum.AUDIT_SUCCESS);
        if (!updated) {
            log.error("EventDetailBackendService#testEventDetailProperty 测试验证通过后状态调整失败 入参：【{}】", JSONObject.toJSONString(req));
            throw new BizException(BizErrorCodeEnum.OPERATION_FAILED, "请稍后重拾");
        }
        return new BizResponse<>(eventInfoModel.getNewPayload().toJSONString());
    }

    @Override
    public BizResponse<Boolean> enableEventDetail(EnableEventDetailReq req) {
        if (req == null || req.getId() == null || req.getEnable() == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        EventDetailBO eventDetailBO = eventDetailService.queryEventDetail(req.getId());
        if (eventDetailBO == null) {
            log.error("EventDetailBackendService#enableEventDetail 查询事件详情失败 入参：【{}】", JSONObject.toJSONString(req));
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        if (eventDetailBO.getStatus().equals(EventDetailStatusEnum.RUNNING) && req.getEnable()) {
            log.info("EventDetailBackendService#enableEventDetail 操作成功，当前状态已经为运行状态  入参：【{}】", JSONObject.toJSONString(req));
            return BizResponse.success(true);
        }
        if (eventDetailBO.getStatus().equals(EventDetailStatusEnum.SHUTDOWN) && !req.getEnable()) {
            log.info("EventDetailBackendService#enableEventDetail 操作成功，当前状态已经为停止状态  入参：【{}】", JSONObject.toJSONString(req));
            return BizResponse.success(true);
        }
        if (req.getEnable()) {
            if (eventDetailBO.getStatus().equals(EventDetailStatusEnum.DRAFT)) {
                log.error("EventDetailBackendService#enableEventDetail 当前状态不允许操作，入参：【{}】", JSONObject.toJSONString(req));
                throw new BizException(BizErrorCodeEnum.PARAM_ERROR, "当前状态不允许操作");
            }
        }
        Boolean updated = eventDetailService.updateEventDetailStatus(req.getId(), eventDetailBO.getStatus(), req.getEnable() ? EventDetailStatusEnum.RUNNING : EventDetailStatusEnum.SHUTDOWN);
        return BizResponse.success(updated);
    }

    @Override
    public BizResponse<EventDetailResp> queryEventDetailById(QueryEventDetailByIdReq req) {
        EventDetailBO eventDetailBO = eventDetailService.queryEventDetail(req.getEventId());
        log.info("EventDetailBackendService#queryEventDetailById 查询事件详情完成 入参：【{}】，出参：【{}】", JSONObject.toJSONString(req), JSONObject.toJSONString(eventDetailBO));
        return BizResponse.success(EventActivityConvert.convertToEventDetailResp(eventDetailBO));
    }

    @Override
    public BizPageResponse<EventInfoResp> queryEventDetailPage(QueryEventDetailPageReq req) {
        if (req == null || !req.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        EventInfoConditionBO conditionBO = EventActivityConvert.convertToEventInfoConditionBO(req);
        PageResult<EventInfoBO> pageResult = eventDetailService.queryEventInfoPageByCondition(conditionBO);
        return BizPageResponse.success(EventActivityConvert.convertToEventInfoRespPage(pageResult));
    }
}
